package com.luoqy.speedy.modular.web.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.luoqy.speedy.modular.web.aop.HttpAspect;
import com.luoqy.speedy.util.HttpApi;

/**
 * Jsoup 工具类
 */
public class JsoupUtil {

    private static final Logger log = LoggerFactory.getLogger(HttpAspect.class);
    /**
     * @param content
     * @return 删除Html标签
     */
    public static String delHTMLTag(String content) {
        content = content.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "").replaceAll("[(/>)<]", "");

        // 去除字符串中的空格 回车 换行符 制表符 等

        content = content.replaceAll("\\s*|\t|\r|\n", "");

        // 去除空格
        content = content.replaceAll("&nbsp;", "");

        return content;
    }

    /**
     * 字符串转化为UTF-8
     *
     * @param str
     * @return
     */
    public static String toUTF8(String str) {
        String result = str;
        try {
            result = changeCharSet(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;

    }

    /**
     * @param str
     * @param newCharset
     * @return
     * @throws UnsupportedEncodingException
     */
    private static String changeCharSet(String str, String newCharset) throws UnsupportedEncodingException {
        if (str != null) {
            // 用默认字符编码解码字符串。
            byte[] bs = str.getBytes();
            // 用新的字符编码生成字符串
            return new String(bs, newCharset);
        }
        return str;
    }

    /**
     * @param str
     * @return
     */
    public static String sub(String str) {

        if (!str.isEmpty()) {
            return str.substring(str.indexOf("：") + 1);
        }
        return null;
    }

    public static String subContent(String str) {

        if (!str.isEmpty()) {
            return str.substring(0, str.indexOf("http"));
        }
        return null;
    }
public static void main(String[] args) throws UnsupportedEncodingException {
	Map<String,Object> map=new HashMap<String, Object>();
	map.put("searchkey", "老祖宗在天有灵");
	String listPage=HttpApi.post("http://www.shuquge.com/search.php?searchkey="+URLEncoder.encode("高手寂寞","utf8")+"&oylafc=yddvz1");
	 Document doc = Jsoup.parse(listPage);  
	 System.err.println(doc);
	 Elements elements=doc.select(".bookname");
	 for (Element element : elements) {
		 Document docs=Jsoup.parse(element.select("a").toString());
		 System.err.println(element.select("a").attr("href"));
		 System.err.println(element.select("a").text());
		 System.err.println(element.select("a").attr("abs:href"));
	}
	
}
    /**
     * 获取链接的document对象
     *
     * @param url
     * @return document
     */
    public static Document getDoc(String url) {
	    	boolean flag = false;
	        Document document = null;
	        do {
	            try {
	                document = Jsoup
	                        .connect(url)
	                        .timeout(30000)
	                        .userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36")
	                        .get();
	                flag = false;
	            } catch (IOException e) {
	                // TODO 自动生成的 catch 块
	                //e.printStackTrace();
	            	if(isConnection(url)){
	            		System.err.println("链接超时并开始重新连接:"+url);
		                flag = true;
	            	}else{
	            		System.err.println("不存在的链接:"+url);
		                flag = false;
	            	}
	            	
	            }
	        } while (flag);
	        return document;	
        
    }
    public static boolean isConnection(String url) {
        boolean flag = false;
        if (null == url || url.length() <= 0) {
            return flag;
        }
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            int state = connection.getResponseCode();
            if (state == 200) {
                flag = true;
            }else{
            	flag=false;
            }
            return flag;
        } catch (Exception e) {
        	//e.printStackTrace();
        	return flag;
        }
       
    }
}
